package com.zmh.service.httpclient;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmh.common.DateUtil;
import com.zmh.common.FileUtil;
import com.zmh.common.OperationUtil;
import com.zmh.common.QRCodeHandler;
import com.zmh.dao.WimageDao;
import com.zmh.model.httpclient.HttpHeader;
import com.zmh.model.wechat.httpClient.Wimage;

/**
 * @author zhoumh
 * @version 创建时间：2017年10月20日 下午2:16:50
 * @Description
 */
@Service
public class WeChat {
	private static Logger logger = LoggerFactory.getLogger(WeChat.class);
	private static final String separator = File.separator;

	@Autowired
	private HttpConnectionManager httpConnectionManager;
	@Autowired
	private WimageDao wimageDao;
	@Autowired
	private QRCodeHandler qrCodeHandler;
	private static CloseableHttpClient httpClient = null;
	private static CloseableHttpResponse response = null;
	private static Header[] headers = null ;
	private static String token ;
	private static HttpClientContext httpContext = HttpClientContext.create();;
	@PostConstruct
	public void init() {
		getHttpClient();
	}
	@PreDestroy
	public void dostory() {
		closeHttpClient();
	}

	/**
	 * 根据openid发送消息
	 * @return boolean true 发送消息成功 false 发送消息失败
	 * @author zhoumh
	 * @version 创建时间：2017年10月12日 下午5:32:23
	 */
	public boolean sendMessge(String openid, String content){
		boolean result = false;
//		在方法调用处进行验证
//		if(!isLogin()){
//			//如果不是登录状态就重新登录并赋值token
//			logger.error("微信未登录，请扫码登陆！");
//			return result;
//		}
		String sendMessgeUrl = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token="+token+"&lang=zh_CN";
		headers = HttpHeader.custom()
				.accept("application/json, text/javascript, */*; q=0.01")
				.xRequestedWith("XMLHttpRequest")
				.referer("https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&tofakeid="+openid+"&token="+token+"&lang=zh_CN")
				.acceptLanguage("zh-CN")
				.acceptEncoding("gzip, deflate")
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
				.contentType("application/x-www-form-urlencoded; charset=UTF-8")
				.host("mp.weixin.qq.com")
				.connection("Keep-Alive")
				.build();
		// 设置POST参数 token=1926935737&lang=zh_CN&f=json&ajax=1&random=0.417206422435307&type=1&content=消息内容测试&tofakeid=oq8Y20dXcYxg4Pk_dI6VVtnLZM0Q&imgcode=
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("token", token));
		formparams.add(new BasicNameValuePair("lang", "zh_CN"));
		formparams.add(new BasicNameValuePair("f", "json"));
		formparams.add(new BasicNameValuePair("random", OperationUtil.getRandomWechat()));
		formparams.add(new BasicNameValuePair("type", "1"));
		formparams.add(new BasicNameValuePair("content", content));
		formparams.add(new BasicNameValuePair("tofakeid", openid));
		formparams.add(new BasicNameValuePair("imgcode", ""));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			response = doPost(sendMessgeUrl, uefEntity);
    		HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {  
	            if (entity != null) {  
	            	String rs = EntityUtils.toString(entity, "UTF-8");
					result = true;
					//判断是否48小时未发生对话  {"base_resp":{"err_msg":"customer block","ret":10706}}
					if (rs.indexOf("block") == 34) {
						logger.error("发送失败，48小时未发生对话，已被锁定！");
						result = false;
					}
	            }
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		} 
		//预期返回值：{"base_resp":{"err_msg":"","ret":0}}
		logger.info("sendMessge()发送结果: "+result+"\n ");
		return result;
	}
	/**
	 * 获取图片素材信息并插入数据库中
	 * @return 
	 * @return: String
	 * @author: zhoumh
	 * @version: 创建时间：2017年12月28日 下午4:19:44 
	 * @Description:
	 */
	public void getImgList(){
		String url = "https://mp.weixin.qq.com/cgi-bin/filepage?type=2&begin=0&count=100&t=media/img_list&group_id=101&token="+token+"&lang=zh_CN&token="+token+"&lang=zh_CN&f=json&ajax=1&random="+OperationUtil.getRandomWechat();
		String html = getHTML(url);
		JSONArray items = JSON.parseObject(html).getJSONObject("page_info").getJSONArray("file_item");
		logger.info(items.toJSONString());
		for (int i = 0; i < items.size(); i++) {
			JSONObject item = items.getJSONObject(i);
			Wimage wimage = new Wimage();
			wimage.setName(item.getString("name"));
			wimage.setWid(item.getString("file_id"));
			wimage.setWurl(item.getString("cdn_url"));
			wimage.setType(item.getString("img_format"));
			wimage.setSize(item.getString("size"));
			wimageDao.insWimage(wimage);
		}
//		JSONObject item = JSON.parseObject(appmsg);
//		JSONArray item = JSON.parseArray(appmsg);
//		System.out.println(item.getJSONObject(0).getString("author"));
//		JSONArray multiItem = item.getJSONObject(0).getJSONArray("multi_item");
//		System.out.println(item.getJSONObject(0).getJSONArray("multi_item").getJSONObject(0).getString("author"));
//		System.out.println(item.getJSONObject(0).getJSONArray("multi_item").getJSONObject(0).getString("content"));
	}
	/**
	 * 获取所有图文消息
	 * @return 
	 * @return: String
	 * @author: zhoumh
	 * @version: 创建时间：2017年12月28日 下午4:19:44 
	 * @Description:
	 */
	public String getAppMsgList(){
		String appmsg = "";
		String url = "https://mp.weixin.qq.com/cgi-bin/appmsg?begin=0&count=10&t=media/appmsg_list2&type=10&action=list_card&token="+token+"&lang=zh_CN";
		String html = getHTML(url);
		Document doc = Jsoup.parse(html);
		// 获取所有script
		Elements scripts  = doc.select("script");
		// 循环遍历所有script
		for (Element script : scripts) {
			if (script.html().contains("document.domain = ")) {
//				logger.info(">>>>>>>>>>>>>infos>>>>>>>>>>>>>>>>>>> \n"+script);
				// 转成字符串
				String st = script.toString();
				appmsg = st.substring(st.indexOf(":[{")+1,st.indexOf("}]}")+2);
//				logger.info(HtmlUtils.htmlUnescape(appmsg));
			}
		}
		return appmsg;
	}
	/**
	 * 根据图文消息ID获取图文消息内容
	 * @param appmsgid 消息ID
	 * @return: String 图文消息内容
	 * @author: zhoumh
	 * @version: 创建时间：2017年12月14日 下午2:38:48 
	 * @Description:
	 */
	public String getAppMsgById(String appmsgid){
		String appmsg = "";
		String url = "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&lang=zh_CN&token="+token+"&type=10&appmsgid="+appmsgid+"&isMul=1";
		String html = getHTML(url);
		Document doc = Jsoup.parse(html);
		// 获取所有script
		Elements scripts  = doc.select("script");
		// 循环遍历所有script
		for (Element script : scripts) {
			if (script.html().contains("document.domain = ")) {
				// 转成字符串
				String st = script.toString();
				appmsg = st.substring(st.indexOf(":[{")+1,st.indexOf("}]}")+2);
//				logger.info(HtmlUtils.htmlUnescape(appmsg));
			}
		}
		return appmsg;
	}
	/**
	 * 更新图文消息内容
	 * @return: boolean true 更新成功 false 更新失败
	 * @author: zhoumh
	 * @version: 创建时间：2017年12月11日 下午2:30:11 
	 * @Description: 
	 */
	public boolean updAppMsg(String appMsg){
		boolean result = false;
//		logger.info(appMsg);
		JSONObject item = JSON.parseArray(appMsg).getJSONObject(0);
		JSONObject multiItem = item.getJSONObject("multi_item");
		String url = "https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=update&type=10&token="+token+"&lang=zh_CN";
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("token", token));
		formparams.add(new BasicNameValuePair("lang", "zh_CN"));
		formparams.add(new BasicNameValuePair("f", "json"));
		formparams.add(new BasicNameValuePair("ajax", "1"));
		formparams.add(new BasicNameValuePair("random", OperationUtil.getRandomWechat()));
		formparams.add(new BasicNameValuePair("AppMsgId", item.getString("app_id")));
		formparams.add(new BasicNameValuePair("count", "1"));
		formparams.add(new BasicNameValuePair("data_seq", item.getString("data_seq")));
		formparams.add(new BasicNameValuePair("operate_from", "Chrome"));
		formparams.add(new BasicNameValuePair("title0", multiItem.getString("title")));
		formparams.add(new BasicNameValuePair("content0", HtmlUtils.htmlUnescape(multiItem.getString("content"))));
		formparams.add(new BasicNameValuePair("digest0", multiItem.getString("digest")));
		formparams.add(new BasicNameValuePair("author0", multiItem.getString("author")));
		formparams.add(new BasicNameValuePair("fileid0", multiItem.getString("fileid")));
		formparams.add(new BasicNameValuePair("cdn_url0", multiItem.getString("cdn_url")));
		formparams.add(new BasicNameValuePair("cdn_url_back0", multiItem.getString("cdn_url_back")));
		formparams.add(new BasicNameValuePair("music_id0", ""));
		formparams.add(new BasicNameValuePair("video_id0", ""));
		formparams.add(new BasicNameValuePair("show_cover_pic0", multiItem.getString("show_cover_pic")));
		formparams.add(new BasicNameValuePair("shortvideofileid0", ""));
		formparams.add(new BasicNameValuePair("vid_type0", ""));
		formparams.add(new BasicNameValuePair("copyright_type0", multiItem.getString("copyright_type")));
		formparams.add(new BasicNameValuePair("releasefirst0", ""));
		formparams.add(new BasicNameValuePair("platform0", ""));
		formparams.add(new BasicNameValuePair("reprint_permit_type0", ""));
		formparams.add(new BasicNameValuePair("original_article_type0", ""));
		formparams.add(new BasicNameValuePair("can_reward0", multiItem.getString("can_reward")));
		formparams.add(new BasicNameValuePair("reward_wording0", multiItem.getString("reward_wording")));
		formparams.add(new BasicNameValuePair("reward_money0", multiItem.getString("reward_money")));
		formparams.add(new BasicNameValuePair("need_open_comment0", multiItem.getString("need_open_comment")));
		formparams.add(new BasicNameValuePair("only_fans_can_comment0", "0"));
		formparams.add(new BasicNameValuePair("sourceurl0", multiItem.getString("sourceurl")));
		formparams.add(new BasicNameValuePair("free_content0", multiItem.getString("free_content")));
		formparams.add(new BasicNameValuePair("fee0", "0"));
		formparams.add(new BasicNameValuePair("voteid0", ""));
		formparams.add(new BasicNameValuePair("voteismlt0", ""));
		formparams.add(new BasicNameValuePair("supervoteid0", ""));
		formparams.add(new BasicNameValuePair("cardid0", ""));
		formparams.add(new BasicNameValuePair("cardquantity0", ""));
		formparams.add(new BasicNameValuePair("cardlimit0", ""));
		formparams.add(new BasicNameValuePair("ori_white_list0", multiItem.getString("ori_white_list")));
		formparams.add(new BasicNameValuePair("ad_id0", ""));
		formparams.add(new BasicNameValuePair("guide_words0", ""));
		formparams.add(new BasicNameValuePair("is_share_copyright0", "0"));
		formparams.add(new BasicNameValuePair("share_copyright_url0", ""));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			response = doPost(url, uefEntity);
    		HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {  
	            if (entity != null) {  
	            	String rs = EntityUtils.toString(entity, "UTF-8");
					result = true;
//					logger.info(rs);
					//判断是否修改成功 {"appMsgId":100000146,"base_resp":{"err_msg":"","ret":0},"data_seq":539730008,"filter_content_html":[{}],"is_ad_optioal":0,"msg":"","ret":"0"}
//					if (rs.indexOf("block") == 34) {
//						logger.error("发送失败，48小时未发生对话，已被锁定！");
//						result = false;
//					}
	            }
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}
	
	public boolean sendAppMsg(String appId){
		boolean result = false;
		String url = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token="+token+"&lang=zh_CN";
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("token", token));
		formparams.add(new BasicNameValuePair("lang", "zh_CN"));
		formparams.add(new BasicNameValuePair("f", "json"));
		formparams.add(new BasicNameValuePair("ajax", "1"));
		formparams.add(new BasicNameValuePair("random", OperationUtil.getRandomWechat()));
		formparams.add(new BasicNameValuePair("type", "10"));
		formparams.add(new BasicNameValuePair("app_id", appId));
		formparams.add(new BasicNameValuePair("isMulti", "0"));
		formparams.add(new BasicNameValuePair("tofakeid", "oq8Y20dXcYxg4Pk_dI6VVtnLZM0Q"));
		formparams.add(new BasicNameValuePair("appmsgid", appId));
		formparams.add(new BasicNameValuePair("imgcode", ""));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			response = doPost(url, uefEntity);
    		HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {  
	            if (entity != null) {  
	            	String rs = EntityUtils.toString(entity, "UTF-8");
					result = true;
//					logger.info(rs);
					//判断是否48小时未发生对话  {"base_resp":{"err_msg":"customer block","ret":10706}}
					if (rs.indexOf("block") == 34) {
						logger.error("发送失败，48小时未发生对话，已被锁定！");
						result = false;
					}
	            }
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 判断是否还处于登录状态
	 * @return: boolean true 登录 false 退出
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月27日 下午3:48:49 
	 * @Description:
	 */
	public boolean isLogin(){
		boolean result = true;
		if (OperationUtil.isEmpty(token)) {
			//如果全局token为空，直接返回false重新登录
			return false;
		}
		String managerUrl = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token="+token;
		headers = HttpHeader.custom()
				.accept("text/html, application/xhtml+xml, image/jxr, */*")
				.referer("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com")
				.acceptLanguage("zh-CN")
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
				.acceptEncoding("gzip, deflate")
				.host("mp.weixin.qq.com")
				.connection("Keep-Alive")
				.build();
		String html = getHTML(managerUrl);
		Document doc = Jsoup.parse(html);
		String state = doc.select("h2 > a[href=/]").text();
		//如果状态不为空，且状态值为登录或返回首页就认定为需要重新登录
		if (!OperationUtil.isEmpty(state)&&("登录".equals(state)||"返回首页".equals(state))) {
			logger.info(state);
			result = false;
		}
		logger.info("是否登录验证结果"+result);
		return result;
	}
	


	/**
	 * 发起登陆请求并获取最新登陆二维码
	 * @return String 获取的登陆链接
	 * @author zhoumh
	 * @version 创建时间：2017年11月6日 下午7:43:32 
	 */
	public String getQrcode(){
		String result = "";
		//请求登录页面，获得初始化cookie设置
		headers= HttpHeader.custom()
				.accept("text/html, application/xhtml+xml, image/jxr, */*")
				.acceptLanguage("zh-CN")
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
				.acceptEncoding("gzip, deflate")
				.host("mp.weixin.qq.com")
				.connection("Keep-Alive")
				.build();
		getHTML("https://mp.weixin.qq.com/");
		//登录
		startlogin();
		//获取二维码图片
		result = getImg();

		return result;
	}
	/**
	 * 验证二维码是否成功被验证，验证成功就刷新token
	 * @return: String 0 登陆失败，4 扫码成功 1 登陆且获取token成功
	 * @author: zhoumh
	 * @version: 创建时间：2017年11月6日 下午7:43:32 
	 * @Description:
	 */
	public String checkQrcode(){
		String state = "5";
		String checkUrl = "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1";
	    String html = getHTML(checkUrl);
	    logger.info(html);
	    if (html.indexOf("4")>0) {
	    	logger.info("微信扫码成功！");
	    	state = "4";
		}
	    if (html.indexOf("1")>0) {
	    	logger.info("微信登录成功！");
	    	//获取token
	    	if (getToken()) {
	    		state = "1";
	    	}else{
	    		logger.error("获取token失败");
	    		state = "0";
	    	}
		}
	    return state;
	}
	/**
	 * 刷新登陆状态
	 * @return: boolean true 依然在登录状态  false 不在登录状态
	 * @author: zhoumh
	 * @version: 创建时间：2017年11月10日 下午8:13:33 
	 * @Description:
	 */
	public boolean refreshLogin(){
		boolean result = true;
		String managerUrl = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token="+token;
		getHTML(managerUrl);
		return result;
	}
	/**
	 * 获取用户向公众号发送的最后一条
	 * @return: String lastMsgID与lastTime
	 * @author: zhoumh
	 * @version: 创建时间：2017年11月13日 下午2:26:23 
	 * @Description:
	 */
	public String[] getLastMessage() {
		String lastTime = "";
		String lastMsgId = "";
		if(!isLogin()){
			//如果不是登录状态就重新登录并赋值token
			logger.error("微信未登录，请扫码登陆！");
			return new String[]{};
		}
		String url = "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&token="+token+"&count=20&day=7";
		String html = getHTML(url);
		Document doc = Jsoup.parse(html);
		// 获取所有script
		Elements scripts  = doc.select("script");
		for (Element script : scripts) {
			if (script.html().contains("wx.cgiData")) {
//				logger.info(">>>>>>>>>>>>>cgiData>>>>>>>>>>>>>>>>>>> \n"+script);
				// 转成字符串
				String st = script.toString();
				lastMsgId = st.substring(st.indexOf("latest_msg_id")+17,st.lastIndexOf("count")-15);
				String msg_item = st.substring(st.indexOf(":[{")+1,st.indexOf("}]}")+2);
				JSONArray items =JSON.parseArray(msg_item);
				for (int i = 0; i < items.size(); i++) {
					JSONObject item = items.getJSONObject(i);
					// 根据最后一条消息ID进行匹配
					if (lastMsgId.equals(item.getString("id"))) {
						// 获取最后发送时间转换成时间格式
						lastTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Long.parseLong(item.getString("date_time")+"000"));
						break;
					}
				}
				break;
			}
		}
//		System.out.println(lastMsgId+"    "+lastTime);
		return new String[]{lastMsgId,lastTime};
	}

	/**
	 * 发起账号登录请求
	 * @return true 登录成功 false 登录失败
	 * @author zhoumh
	 * @version 创建时间：2017年10月12日 下午5:32:23
	 */
	private boolean startlogin(){
		boolean result = false;
		CloseableHttpResponse response = null;
		// 设置POST参数 username=zmh1812%40qq.com&pwd=0c7bdf291df52b4a6bde1fb3c903c4b5&imgcode=&f=json&token=&lang=zh_CN&ajax=1
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("username", "zmh1812@qq.com"));
		formparams.add(new BasicNameValuePair("pwd", "0c7bdf291df52b4a6bde1fb3c903c4b5"));
		formparams.add(new BasicNameValuePair("imgcode", ""));
		formparams.add(new BasicNameValuePair("f", "json"));
		formparams.add(new BasicNameValuePair("token", ""));
		formparams.add(new BasicNameValuePair("lang", "zh_CN"));
		formparams.add(new BasicNameValuePair("ajax", "1"));
		UrlEncodedFormEntity uefEntity;
		headers = HttpHeader.custom()
				.accept("*/*")
				.contentType("application/x-www-form-urlencoded; charset=UTF-8")
				.xRequestedWith("XMLHttpRequest")
				.referer("https://mp.weixin.qq.com/")
				.acceptLanguage("zh-CN")
				.acceptEncoding("gzip, deflate")
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
				.host("mp.weixin.qq.com")
				.connection("Keep-Alive")
				.cacheControl("no-cache")
				.build();
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			// 发起登录请求
			response = doPost("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin", uefEntity);
			if (response.getStatusLine().getStatusCode()==200) {
				HttpEntity entity = response.getEntity();
				// 判断返回实体是否为空
				if (entity != null) {
					// 获取返回的内容
					String html = EntityUtils.toString(entity, "UTF-8");
					//判断返回值是否符合预期：{"base_resp":{"err_msg":"ok","ret":0},"redirect_url":"/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com"}
					if (html.indexOf("ok") == 25) {
						result = true;
					}
				}
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		} 
		//预期返回值：{"base_resp":{"err_msg":"ok","ret":0},"redirect_url":"/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com"}
//		logger.info("startlogin()登录请求结果: "+result+"\n ");
		return result;
	}
	
	/**
	 * 获取token
	 * @return boolean true 获取成功 false 获取失败
	 * @author zhoumh
	 * @version 创建时间：2017年10月12日 下午5:32:23
	 */
	private boolean getToken(){
		boolean result = false;
		CloseableHttpResponse response = null;
		// 设置POST参数 token=&lang=zh_CN&f=json&ajax=1
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("token", ""));
		formparams.add(new BasicNameValuePair("lang", "zh_CN"));
		formparams.add(new BasicNameValuePair("f", "json"));
		formparams.add(new BasicNameValuePair("ajax", "1"));
		UrlEncodedFormEntity uefEntity;
		headers = HttpHeader.custom()
				.accept("*/*")
				.contentType("application/x-www-form-urlencoded; charset=UTF-8")
				.xRequestedWith("XMLHttpRequest")
				.referer("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com")
				.acceptLanguage("zh-CN")
				.acceptEncoding("gzip, deflate")
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
				.host("mp.weixin.qq.com")
				.connection("Keep-Alive")
				.cacheControl("no-cache")
				.build();
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			// Post请求  
			response = doPost("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login",uefEntity);
			if (response.getStatusLine().getStatusCode()==200) {
				// 获取返回消息实体
				HttpEntity entity = response.getEntity();
				// 判断返回实体是否为空
				if (entity != null) {
					// 获取返回的内容  {"base_resp":{"err_msg":"ok","ret":0},"redirect_url":"/cgi-bin/home?t=home/index&lang=zh_CN&token=1565329723"}
					String content = EntityUtils.toString(entity, "UTF-8");
					if (content.indexOf("ok") == 25) {
						//从返回内容中截取token
						token = content.substring(content.lastIndexOf("token=")+6,content.lastIndexOf("\"}"));
						if (!OperationUtil.isEmpty(token)) {
							//token赋值成功返回true
							result = true;
						}
					}
//					System.out.println("response content（返回的内容）:"+token+" \n " + content);
				}
			}
			
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		} 
//		logger.info("getToken: "+token+"\n ");
		return result;
	}
	/** 
     * 保存图片 
     * @param url
     * @throws Exception 
     * @return: void
     * @author: zhoumh
     * @version: 创建时间：2017年10月20日 下午5:32:38 
     * @Description: 可以尝试直接从URL获取文件流保存，并不需要通过httpclient
     */
	private String getImg() {  
		String result = "";
//        String filePath = FileUtil.getStaticPath()+"/src/main/webapp/static/images/" + "qrcode.jpg";
        String filePath = FileUtil.getSysPath()+separator+"static"+separator+"images"+ separator + "qrcode.jpg";
        FileUtil.deleteFile(filePath);
        BufferedOutputStream out = null;  
        //获取登陆认证二维码的字节流
        byte[] bit = getByte("https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=getqrcode&param=4300&rd=283");  
        if (bit.length > 0) {  
            try {  
                out = new BufferedOutputStream(new FileOutputStream(filePath));  
                out.write(bit);  
                out.flush();  
                result = qrCodeHandler.decoderQRCode(filePath);
                logger.info("Create File success! [" + filePath + "]"+result);  
            }catch (Exception e) {
            	 e.printStackTrace();  
            } finally {  
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
            }
        }
        return result;
    }  
	/**
     * 获取图片字节流  
     * @param uri
     * @throws Exception 
     * @return: byte[]
     * @author: zhoumh
     * @version: 创建时间：2017年10月20日 下午5:32:29 
     * @Description:
     */
    private byte[] getByte(String url) {  
    	try {
    		response = doGet(url);
    		HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {  
                if (entity != null) {  
                    return EntityUtils.toByteArray(entity);  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return new byte[0];  
    } 
	/**
	 * 根据URL发起请求并返回请求结果
	 * @param url 请求链接
	 * @author zhoumh
	 * @version 创建时间：2017年10月13日 上午10:30:47
	 */
	private String getHTML(String url) {
		String html = "";
		try {
			response = doGet(url);
			HttpEntity entity = response.getEntity();
			// 判断返回实体是否为空
			if (entity != null) {
				// 获取返回的内容
				html = EntityUtils.toString(entity, "UTF-8");
//				logger.info(html);
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return html;
	}
	
	/**
	 * 根据传入的URL和httpclient发起get请求并返回结果
	 * 
	 * @param url   请求的地址
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @return: CloseableHttpResponse
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月17日 上午11:04:45
	 * @Description:
	 */
	private CloseableHttpResponse doGet(String url)
			throws ClientProtocolException, IOException {
		HttpGet httpGet = new HttpGet(url);
		// 配置请求的HEADER部分 
//		httpGet.setHeaders(headers);
		// 接收返回信息
		response = getHttpClient().execute(httpGet, httpContext);
		return response;
	}
	/**
	 * 根据传入的URL和httpclient发起POST请求并返回结果
	 * 
	 * @param url  请求的地址
	 * @param uefEntity 请求的表单
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @return: CloseableHttpResponse
	 * @author: zhoumh
	 * @version: 创建时间：2017年7月26日 下午5:19:23
	 * @Description:
	 */
	private CloseableHttpResponse doPost(String url,
			UrlEncodedFormEntity uefEntity)
			throws ClientProtocolException, IOException {
		// Post请求
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(uefEntity);
		//这个必须设置 否则无法登录
		httppost.setHeaders(headers);
		// 发送请求并接收返回信息
		response = getHttpClient().execute(httppost, httpContext);
		return response;
	}
	/**
	 * 循环输出所有cookie信息
	 *  
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月23日 上午10:21:00 
	 * @Description:
	 */
	private void getCookies(){
		httpContext.getCookieStore().getCookies().forEach(System.out::println);
	}
	/**
	 * 从连接池获取httpclient
	 * 
	 * @return: CloseableHttpClient
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月17日 上午9:45:28
	 * @Description:
	 */
	private CloseableHttpClient getHttpClient() {
		if (httpClient == null) {
			httpClient = httpConnectionManager.getHttpsClient();
			// 设置cookie
//			RequestConfig requestConfig = RequestConfig.custom()
//					.setConnectionRequestTimeout(10000)
//					.setConnectTimeout(10000)
//					.setCookieSpec(CookieSpecs.STANDARD_STRICT)
//					.build();
//			httpClient = HttpClients.custom()
//					.setDefaultRequestConfig(requestConfig)
//					.build();
		}
		return httpClient;
	}
	/**
	 * 关闭httpclient
	 * 
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月17日 上午9:45:50
	 * @Description:
	 */
	private void closeHttpClient() {
		try {
			if (response != null) {
				response.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 发起登陆并赋值token
	 * @return boolean true 登录成功 false 登录失败
	 * @author zhoumh
	 * @version 创建时间：2017年10月12日 下午5:32:23
	 * @deprecated 前端获取二维码之后方法被拆分成getQrcode和checkQrcode，此方法废弃不再使用
	 */
	public boolean login(){
		boolean result = false;
		//请求登录页面，获得初始化cookie设置
		headers= HttpHeader.custom()
				.accept("text/html, application/xhtml+xml, image/jxr, */*")
				.acceptLanguage("zh-CN")
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
				.acceptEncoding("gzip, deflate")
				.host("mp.weixin.qq.com")
				.connection("Keep-Alive")
				.build();
		getHTML("https://mp.weixin.qq.com/");
		//登录
		startlogin();
		//获取二维码图片
		getImg();
		//生成二维码之后持续扫描是否验证二维码，进程等待确认，持续十分钟就停止询问，等待重新生成二维码
		String checkUrl = "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1";
		String beginTime = DateUtil.getDateTimes();
		while(true){
			try {
				//每3s查询是一次是否扫码成功
			    Thread.sleep(3000);      
			    // 如果获取二维码时间超过3分钟
			    if (DateUtil.getMinDiff(beginTime)>3) {
			    	logger.error("微信二维码超时，取消登陆！");
		    		return false;
				}
			    String html = getHTML(checkUrl);
			    logger.info(html);
			    if (html.indexOf("4")>0) {
			    	logger.info("微信扫码成功！");
				}
			    if (html.indexOf("1")>0) {
			    	logger.info("微信登录成功！");
					break;
				}
			} catch(InterruptedException ex) {
			    Thread.currentThread().interrupt();
			}
		}
		//获取token
		if (getToken()) {
			result = true;
		}else{
			logger.error("获取token失败");
			result = false;
		}
		return result;
	}
	
	 private void temp() {
//			headers = HttpHeader.custom()
//			.accept("text/html, application/xhtml+xml, image/jxr, */*")
//			.referer("https://mp.weixin.qq.com/")
//			.acceptLanguage("zh-CN")
//			.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
//			.acceptEncoding("gzip, deflate")
//			.host("mp.weixin.qq.com")
//			.connection("Keep-Alive")
//			.build();
//	getHTML("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812@qq.com");
//	headers = HttpHeader.custom()
//			.accept("*/*")
//			.xRequestedWith("XMLHttpRequest")
//			.referer("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com")
//			.acceptLanguage("zh-CN")
//			.acceptEncoding("gzip, deflate")
//			.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
//			.host("mp.weixin.qq.com")
//			.connection("Keep-Alive")
//			.build();
//	getHTML("https://mp.weixin.qq.com/misc/faq?action=getfaq&lang=zh_CN&f=json&cginame=cgi-bin/bizlogin&action=validate");
//		   String jsmonitor = "https://mp.weixin.qq.com/mp/jsmonitor?idkey=67324_123_1";
//			headers = HttpHeader.custom()
//					.accept("image/png, image/svg+xml, image/jxr, image/*;q=0.8, */*;q=0.5")
//					.referer("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com")
//					.acceptLanguage("zh-CN")
//					.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
//					.acceptEncoding("gzip, deflate")
//					.host("mp.weixin.qq.com")
//					.connection("Keep-Alive")
//					.build();
//			//{"ret":0,"errmsg":"ok","cookie_count":0}
//			getHTML(jsmonitor);
//			String jslog = "https://mp.weixin.qq.com/misc/jslog?id=98&content=scanLoginSuccess&level=error";
//			getHTML(jslog);
//			String managerUrl = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token="+token;
//			headers = HttpHeader.custom()
//					.accept("text/html, application/xhtml+xml, image/jxr, */*")
//					.referer("https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=zmh1812%40qq.com")
//					.acceptLanguage("zh-CN")
//					.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
//					.acceptEncoding("gzip, deflate")
//					.host("mp.weixin.qq.com")
//					.connection("Keep-Alive")
//					.build();
//			getHTML(managerUrl);
//			Map<String, Header> headerMaps = new HashMap<String, Header>(); 
//			headerMaps.put("Accept", new BasicHeader("Accept", ""));
//			headerMaps.put("Accept-Charset", new BasicHeader("Accept-Charset", ""));
//			headerMaps.put("Accept-Encoding", new BasicHeader("Accept-Encoding", ""));
//			headerMaps.put("Accept-Language", new BasicHeader("Accept-Language", ""));
//			headerMaps.put("Accept-Ranges", new BasicHeader("Accept-Ranges", ""));
//			headerMaps.put("Authorization", new BasicHeader("Authorization", ""));
//			headerMaps.put("Cache-Control", new BasicHeader("Cache-Control", ""));
//			headerMaps.put("Connection", new BasicHeader("Connection", ""));
//			headerMaps.put("Cookie", new BasicHeader("Cookie", ""));
//			headerMaps.put("Content-Length", new BasicHeader("Content-Length", ""));
//			headerMaps.put("Content-Type", new BasicHeader("Content-Type", ""));
//			headerMaps.put("Date", new BasicHeader("Date", ""));
//			headerMaps.put("Expect", new BasicHeader("Expect", ""));
//			headerMaps.put("From", new BasicHeader("From", ""));
//			headerMaps.put("Host", new BasicHeader("Host", ""));
//			headerMaps.put("If-Match", new BasicHeader("If-Match", ""));
//			headerMaps.put("If-Modified-Since", new BasicHeader("If-Modified-Since", ""));
//			headerMaps.put("If-None-Match", new BasicHeader("If-None-Match", ""));
//			headerMaps.put("If-Range", new BasicHeader("If-Range", ""));
//			headerMaps.put("If-Unmodified-Since", new BasicHeader("If-Unmodified-Since", ""));
//			headerMaps.put("Keep-Alive", new BasicHeader("Keep-Alive", ""));
//			headerMaps.put("Max-Forwards", new BasicHeader("Max-Forwards", ""));
//			headerMaps.put("Pragma", new BasicHeader("Pragma", ""));
//			headerMaps.put("Proxy-Authorization", new BasicHeader("Proxy-Authorization", ""));
//			headerMaps.put("Range", new BasicHeader("Range", ""));
//			headerMaps.put("Referer", new BasicHeader("Referer", ""));
//			headerMaps.put("TE", new BasicHeader("TE", ""));
//			headerMaps.put("Upgrade", new BasicHeader("Upgrade", ""));
//			headerMaps.put("User-Agent", new BasicHeader("User-Agent", ""));
//			headerMaps.put("Via", new BasicHeader("Via", ""));
//			headerMaps.put("Warning", new BasicHeader("Warning", ""));
//			headerMaps.put("X-Requested-With", new BasicHeader("X-Requested-With", ""));

	}

}
